import pandas as pd
import numpy as np
from django.http import JsonResponse
from scipy.interpolate import lagrange  # 导入拉格朗日插值函数
from sklearn.linear_model import LinearRegression

from db.models import *

data = pd.read_excel('db/成都.xlsx')


# 一元线性回归插补
def liner(x, y, n):
    model = LinearRegression()
    model.fit(x, y)
    return model.predict([[n]])


def process(d):
    for i in data['year'][d.count():]:
        c = d.count()
        d.iloc[c] = liner(data[['year']][0:c], d[0:c], i)
        c+1


# 插入数据
def data_cheng(request):
    # 线性插补
    data['carbon_dioxide'].interpolate(
        inplace=True, method='linear', limit_direction='both')
    process(data['gdp'])
    process(data['energy_c'])
    process(data['gas_c'])
    process(data['oil_c'])

    for d in data.itertuples():
        economy.objects.create(
            year=d.year, gdp=d.gdp, per_income=d.per_income, cpi=d.cpi, eva=d.eva, city='chengdu')
    for d in data.itertuples():
        ecology.objects.create(year=d.year, forest_cover=d.forest_cover, forest_area=d.forest_area, water_resource=d.water_resource,
                               dirty_water=d.dirty_water, city='chengdu')
    for d in data.itertuples():
        carbon.objects.create(year=d.year, raw_coal=d.raw_coal, natural_gas=d.natural_gas, oil=d.oil,
                              carbon_dioxide=d.carbon_dioxide, city='chengdu')
    for d in data.itertuples():
        energy.objects.create(year=d.year, energy_c=d.energy_c, coal_c=d.coal_c, gas_c=d.gas_c, oil_c=d.oil_c,
                              electricity_c=d.electricity_c, city='chengdu')

    return JsonResponse({'message': '成功'})
